package com.port.port_app.service;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class ExcelService {

    //文件存放路径
    public static String PASH = "src" + File.separator + "main" + File.separator + "resources" + File.separator + "files" + File.separator;


    private static final String FILE_NAME = "ATResults.xlsx";

    public void writeToExcel(String[] responses) {
        File file = new File(PASH+ FILE_NAME);
        Workbook workbook;
        Sheet sheet;
        if (file.exists()) {
            try (InputStream is = new FileInputStream(file)) {
                workbook = WorkbookFactory.create(is);
                sheet = workbook.getSheetAt(0);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        } else {
            workbook = new XSSFWorkbook();
            sheet = workbook.createSheet("Responses");
        }

        int rowNum = sheet.getLastRowNum();
        Row row = sheet.createRow(rowNum + 1);
        for (int i = 0; i < responses.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(responses[i]);
            //System.out.println("写入数据="+responses[i]);
        }

        try (OutputStream os = new FileOutputStream(PASH+FILE_NAME)) {
            workbook.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

